﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Management;
using System.Timers;
using System.Net;

namespace ipListener
{
    public partial class Service1 : ServiceBase
    {
       
        public string old_msg;
        private SendMail email;
        public System.Timers.Timer t;
       
        public Service1()
        {
            InitializeComponent();       
            t = new System.Timers.Timer(100000); //实例化Timer类，设置间隔时间为30000毫秒；   
            t.Elapsed += new System.Timers.ElapsedEventHandler(theout);  //到达时间的时候执行事件；   
            t.AutoReset = true;//设置是执行一次（false）还是一直执行(true)；       

        }

        protected override void OnStart(string[] args)
        {
            t.Enabled = true;  
            string msg="";
         
            string hostname = System.Net.Dns.GetHostName();
            System.Net.IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(hostname);
            msg += "========";
            msg = ipEntry.AddressList[0].ToString();
            foreach (IPAddress tmp in ipEntry.AddressList)
            {
                msg += "========";
                msg += tmp.ToString();
            }
            old_msg = msg;

            email = new SendMail("450618400@qq.com", "450618400@qq.com", msg, "ipChanged", "aikang5912881");

            email.mailMessage.Body = "Service of IP listener started";
            email.Send();
        }

        protected override void OnStop()
        {
            t.Enabled = false;
            email.mailMessage.Body = "Service of IP listener stoped";
            email.Send();
          
        }
        public void theout(object source, System.Timers.ElapsedEventArgs e)
        {
            string msg = "";
            string hostname = System.Net.Dns.GetHostName();
            System.Net.IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(hostname);
            msg += "========";
            msg = ipEntry.AddressList[0].ToString();
            foreach (IPAddress tmp in ipEntry.AddressList)
            {
                msg += "========";
                msg += tmp.ToString();
            }
           
            if (msg != old_msg)
            {
                email.mailMessage.Body = msg;
                email.Send();
                old_msg = msg;
            }
        }  

    }
}
